package cn.darkhorse.mesadmin.controller.statement;

import cn.darkhorse.device.dao.LintDetectorDao;
import cn.darkhorse.device.dto.LintDetectorDTO;
import cn.darkhorse.device.iot.constant.IotConstant;
import cn.darkhorse.device.pojo.IotPointTable;
import cn.darkhorse.device.service.IotPointTableService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequestMapping("/lint-detector")
@RestController
public class LintDetectorController extends BaseController {
    @Resource
    private LintDetectorDao lintDetectorDao;
    @Resource
    private IotPointTableService iotPointTableService;

    String gatewayDeviceId="LintDetector";
    String tableName="history_"+gatewayDeviceId;


    /**
     * 查询
     * @param dto
     * @return
     */
    @RequestMapping("/list")
    public TableDataInfo listAll(LintDetectorDTO dto){
        /*if(StringUtils.isNotBlank(dto.getBeginDate())&&StringUtils.isNotBlank(dto.getEndDate())){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            LocalDate begindate=LocalDate.parse(dto.getBeginDate());
            LocalDate enddate=LocalDate.parse(dto.getEndDate());
            dto.setBeginDate(begindate.format(formatter));
            dto.setEndDate(enddate.format(formatter));
        }*/
        startPage();
        dto.setTableName(tableName);
        List<Map<String, Object>> maps = lintDetectorDao.listAll(dto);
        LambdaQueryWrapper<IotPointTable> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(IotPointTable::getGatewayDeviceId,gatewayDeviceId);
        wrapper.eq(IotPointTable::getDataType,1);
        List<IotPointTable> list = iotPointTableService.list(wrapper);
        Map<String, String> collect = list.stream().collect(Collectors.toMap(IotPointTable::getFieldName, IotPointTable::getExtraJson));
        maps.forEach(item->{
            item.forEach((label,value)->{
                if(collect.containsKey(label)){
                    JSONArray jsonArray = JSONArray.parseArray(collect.get(label));
                    if(jsonArray.getJSONObject(0).containsKey("value")) {
                        Object unit = jsonArray.getJSONObject(0).get("value");
                        value += unit.toString();
                        item.put(label,value);
                    }

                }
            });
        });
        return  getDataTable(maps);
    }

    /**
     * 获取批次号集合
     * @return
     */
    @RequestMapping(value = "/batch-num",method = RequestMethod.GET)
    public AjaxResult batchNo(){
        String sql = "SHOW TABLES LIKE '"+tableName+"'";
        List<Map<String, Object>> maps = SqlRunner.db().selectList(sql);
        if(maps.isEmpty()){
            return AjaxResult.success();
        }
        List<String> batchNoList = lintDetectorDao.batchNoList(tableName);
        return AjaxResult.success(batchNoList);
    }


    /**
     * 品质分析
     * @param batchNo
     * @return
     */
    @RequestMapping("/quality")
    public AjaxResult qualityAnalysis(String batchNo){
        if(StringUtils.isBlank(batchNo)){
            return AjaxResult.error("请选择批次号！");
        }
        Map<String,Object> params = new HashMap<>();
        params.put("tableName",tableName);
        params.put("batchNo",batchNo);
        Map<String,Object> result = new HashMap<>();
        Map<String,Object> colorMap = new HashMap<>();
        Map<String,Object> lengthMap = new HashMap<>();
        Map<String,Object> micronaireMap = new HashMap<>();
        Map<String,Object> strengthMap = new HashMap<>();
        Map<String,Object> rollingMap = new HashMap<>();

        List<Map<String, Object>> maps = lintDetectorDao.listByBatchNo(params);
        //点表配置
        List<IotPointTable> assDB = iotPointTableService.list(new LambdaQueryWrapper<IotPointTable>().eq(IotPointTable::getGatewayDeviceId, gatewayDeviceId));
        Map<String, IotPointTable> iptMap = assDB.stream().collect(Collectors.toMap(IotPointTable::getPointId, Function.identity()));

        maps.forEach(item->{

            //颜色级
            countLevel(colorMap,item.get("ColorClass"));
            //长度级
            countLevel(lengthMap,item.get("LengthClass"));
            //马克档次
            countLevel(micronaireMap,item.get("MicronaireClass"));
            //断裂比
            countLevel(strengthMap,item.get("Strength"));
            //轧工质量
            countLevel(rollingMap,item.get("RollingQ"));
        });
        result.put("color",attributeName(colorMap,iptMap.get("ColorClass")));
        result.put("length",attributeName(lengthMap,iptMap.get("LengthClass")));
        result.put("micronaire",attributeName(micronaireMap,iptMap.get("MicronaireClass")));
        result.put("strength",attributeName(strengthMap,iptMap.get("Strength")));
        result.put("rolling",attributeName(rollingMap,iptMap.get("RollingQ")));
        return AjaxResult.success(result);
    }

    /**
     * 级别数量统计
     * @param result
     * @param key
     */
    private void countLevel(Map<String,Object> result,Object key){
        Object obj = result.get(key);
        if(Objects.isNull(obj)){
            obj = 0;
        }
        result.put(key.toString(),Integer.valueOf(obj.toString())+1);
    }

    /**
     * 点表属性翻译
     * @param typeMap
     * @param ipt
     * @return
     */
    private Map<String,Object> attributeName(Map<String,Object> typeMap,IotPointTable ipt){
        Map<String,Object> result = new HashMap<>();
        if(null == ipt || ipt.getDataType().equals(IotConstant.POINT_TYPE_STRING)){
            return typeMap;
        }
        Map<String,String> attributeMap = new HashMap<>();
        JSONArray attributes = JSONArray.parse(ipt.getExtraJson());
        attributes.forEach(item->{
            attributeMap.put(JSONObject.parseObject(item.toString()).getString("label"),
                    JSONObject.parseObject(item.toString()).getString("value"));
        });
        Set<Map.Entry<String, Object>> entries = typeMap.entrySet();
        for(Map.Entry<String, Object> entry:entries){
            String key = attributeMap.get(entry.getKey());
            if(ipt.getDataType().equals(IotConstant.POINT_TYPE_NUMBER)){
                result.put(entry.getKey()+" "+attributeMap.get(attributeMap.keySet().iterator().next()),entry.getValue());
                continue;
            }
            if(StringUtils.isBlank(key)){
                key = entry.getKey();
            }
            result.put(key,entry.getValue());
        }
        return result;
    }


}
